﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using System.Text;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Normal_ChannelController : Controller
    {

        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index(string actionId)
        {
           
            return View("Index");//页面地址
        }


        /// <summary>
        /// 返回功能模块列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            int recordNum = 0;
            QueryParam qp = new QueryParam();
            qp.ReturnFields = "Id,Title,OrderNum,Enabled,IsNav,IsPost,IsHtml,ReId";
            //返回json数组
            if (!string.IsNullOrEmpty(actionId) && actionId.StartsWith("m"))
            {
                qp.PageIndex = 1;
                qp.PageSize = int.MaxValue;

                IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
                List<Normal_ChannelEntity> sys_moduleList = Normal_ChannelSv.List(qp, out recordNum);
                StringBuilder sb = new StringBuilder();
                sb.Append("[");
                GetTreeString(sb, 0, sys_moduleList);
                sb.Append("]");
                returnJson = sb.ToString();

            }
            else
            {
                int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
                int pageIndex = (int)Utils.GetQueryAndFormString("start", this, 9, 1, DataType.Int);
                int parentId = Utils.StringToInt(actionId,0);
                qp.Orderfld = "id asc ";
                qp.PageIndex = pageIndex / pageSize + 1; 
                qp.PageSize = pageSize;
                
                qp.Where = string.Concat(" ReId=", parentId);
                IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
                jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
                IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
                List<Normal_ChannelEntity> normal_channelList = Normal_ChannelSv.List(qp, out recordNum);
                returnJson = string.Concat("{totalPorperty:", recordNum, ",root:", JsonConvert.SerializeObject(normal_channelList, Formatting.Indented, jsDataConvert), "}");
     
            }
            return returnJson;

        }

        /// <summary>
        /// 获取树状json 列表
        /// </summary>
        /// <param name="sb">记录容器</param>
        /// <param name="id">起始id</param>
        /// <param name="list">要循环的列表</param>
        protected void GetTreeString(StringBuilder sb, int id, List<Normal_ChannelEntity> list)
        {
            bool isHasChild = false;
            int intCount = 0;
            int intIndex = 0;
            foreach (Normal_ChannelEntity module in list)
            {
                if (module.ReId == id)
                {
                    intCount++;
                }
            }

            if (intCount != 0)
            {
                foreach (Normal_ChannelEntity module in list)
                {
                    isHasChild = false;
                    if (module.ReId == id)
                    {
                        intIndex++;

                        sb.Append(string.Concat("{text:'", module.Title, "',id:'", module.Id, "'"));

                        foreach (Normal_ChannelEntity module2 in list)
                        {
                            if (module2.ReId == module.Id)
                            {
                                isHasChild = true;
                                sb.Append(",expanded:false,children:[");
                                break;
                            }
                        }
                        GetTreeString(sb, module.Id, list);

                        if (isHasChild)
                        {
                            if (intIndex != intCount)
                            {

                                sb.Append("]},");
                            }
                            else
                            {
                                sb.Append("]}");
                            }
                        }
                        else
                        {
                            if (intIndex != intCount)
                            {
                                sb.Append(",leaf:true},");
                            }
                            else
                            {
                                sb.Append(",leaf:true}");
                            }
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 查看频道 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
            IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
            int intId = Utils.StringToInt(actionId,0);
            Normal_ChannelEntity normal_channel = Normal_ChannelSv.Look(intId);
            if (normal_channel != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(normal_channel), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新频道
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
         [ValidateInput(false)]
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Normal_ChannelEntity normal_channel = new Normal_ChannelEntity();
                normal_channel.DataTable_Action = DataTableAction.Update;
                normal_channel.Id = intId;
                normal_channel.ReId = (Int32)Utils.GetQueryAndFormString("ReId", this, 10, 1, DataType.Int);
                normal_channel.Path = (string)Utils.GetQueryAndFormString("Path", this, 10, 1, DataType.CharAndNum);
                normal_channel.Title = (String)Utils.GetQueryAndFormString("Title", this, 20, 1, DataType.Str);
                normal_channel.SEOTitle = (String)Utils.GetQueryAndFormString("SEOTitle", this, 60, 0, DataType.Str);
                normal_channel.KeyWords = (String)Utils.GetQueryAndFormString("KeyWords", this, 50, 0, DataType.Str);
                normal_channel.Info = (String)Utils.GetQueryAndFormString("Info", this, 200, 1, DataType.Str);
                normal_channel.Dir = (String)Utils.GetQueryAndFormString("Dir", this, 200, 1, DataType.Str);
                if (string.IsNullOrEmpty(normal_channel.Dir))
                {
                    normal_channel.Dir = Utils.ChineseToQuanPin(normal_channel.Title);
                }
                IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
                QueryParam qp2 = new QueryParam();
                qp2.PageIndex = 1;
                qp2.PageSize = 1;
                qp2.Where = string.Concat("dir='", normal_channel.Dir, "' and id!=",intId.ToString());
                int recordNum = 0;
                List<Normal_ChannelEntity> channnelList2 = Normal_ChannelSv.List(qp2, out recordNum);
                if (channnelList2.Count > 0)
                {
                    return "{success:'false',message:'重复的栏目目录'}";
                }
                normal_channel.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10, 1, DataType.Int);
                normal_channel.TemplateId = (Int32)Utils.GetQueryAndFormString("TemplateId", this, 10, 1, DataType.Int);
                normal_channel.ContentTemplateId = (Int32)Utils.GetQueryAndFormString("ContentTemplateId", this, 10, 1, DataType.Int);
                normal_channel.ChannelType = (String)Utils.GetQueryAndFormString("ChannelType", this, 10, 1, DataType.Str);
                normal_channel.Target = (string)Utils.GetQueryAndFormString("Target", this, 10, 1, DataType.CharAndNum);
                normal_channel.Enabled = (bool)Utils.GetQueryAndFormString("Enabled", this, 6,1, DataType.Bool);
                normal_channel.IsNav = (bool)Utils.GetQueryAndFormString("IsNav", this, 6,1, DataType.Bool);
                normal_channel.DefaultThumbs = (Int32)Utils.GetQueryAndFormString("DefaultThumbs", this, 10, 1, DataType.Int);
                normal_channel.IsPost = (bool)Utils.GetQueryAndFormString("IsPost", this, 6,1, DataType.Bool);
                normal_channel.IsHtml = (bool)Utils.GetQueryAndFormString("IsHtml", this, 6,1, DataType.Bool);
                normal_channel.ReadGroup = (Int32)Utils.GetQueryAndFormString("ReadGroup", this, 10, 0, DataType.Int);
                normal_channel.IsPart = (Byte)Utils.GetQueryAndFormString("IsPart", this, 3, 0, DataType.Byte);
                normal_channel.HtmlInfo = (String)Utils.GetQueryAndFormString("HtmlInfo", this, 2147483647, 0, DataType.Str);
                normal_channel.SiteSeoBottom = (String)Utils.GetQueryAndFormString("SiteSeoBottom", this, 1000, 0, DataType.Str);
                normal_channel.SiteImg = (String)Utils.GetQueryAndFormString("SiteImg", this, 200, 0, DataType.Str);
                
                if (Normal_ChannelSv.Update(normal_channel) == "")
                {
                    returnJson = "{success:'true'}";
                    CMN.Framework.MvcWebCacheManager.RemoveNormal_ChannelList();
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }

            return returnJson;
        }

        /// <summary>
        /// 新增频道
        /// </summary>
        /// <returns>json</returns>
         [ValidateInput(false)]
        public string Insert()
        {
            int reid = 0;
            string path = string.Empty;
            Normal_ChannelEntity normal_channel = new Normal_ChannelEntity();
            IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
            normal_channel.DataTable_Action = DataTableAction.Insert;
            normal_channel.ReId = (Int32)Utils.GetQueryAndFormString("ReId", this, 10, 1, DataType.Int);
           // normal_channel.Path = (string)Utils.GetQueryAndFormString("Path", this, 10, 1, DataType.CharAndNum);
            normal_channel.Title = (String)Utils.GetQueryAndFormString("Title", this, 20, 1, DataType.Str);
            normal_channel.SEOTitle = (String)Utils.GetQueryAndFormString("SEOTitle", this, 60, 0, DataType.Str);
            normal_channel.KeyWords = (String)Utils.GetQueryAndFormString("KeyWords", this, 50, 0, DataType.Str);
            normal_channel.Info = (String)Utils.GetQueryAndFormString("Info", this, 200, 1, DataType.Str);
            normal_channel.Dir = (String)Utils.GetQueryAndFormString("Dir", this, 200,0, DataType.Str);
            if (string.IsNullOrEmpty(normal_channel.Dir))
            {
                normal_channel.Dir = Utils.ChineseToQuanPin(normal_channel.Title);
            }
              int recordNum = 0;
            QueryParam qp2 = new QueryParam();
            qp2.PageIndex = 1;
            qp2.PageSize = 1;
            qp2.Where = string.Concat("dir='", normal_channel.Dir, "'");
             List<Normal_ChannelEntity> channnelList2 = Normal_ChannelSv.List(qp2, out recordNum);
             if (channnelList2.Count > 0)
             {
                return  "{success:'false',message:'重复的栏目目录'}";
             }
            normal_channel.OrderNum = (Int32)Utils.GetQueryAndFormString("OrderNum", this, 10, 1, DataType.Int);
            normal_channel.TemplateId = (Int32)Utils.GetQueryAndFormString("TemplateId", this, 10, 1, DataType.Int);
            normal_channel.ContentTemplateId = (Int32)Utils.GetQueryAndFormString("ContentTemplateId", this, 10, 1, DataType.Int);
            normal_channel.ChannelType = (String)Utils.GetQueryAndFormString("ChannelType", this, 10, 1, DataType.Str);
            normal_channel.Target = (string)Utils.GetQueryAndFormString("Target", this, 10, 1, DataType.CharAndNum);
            normal_channel.Enabled = (bool)Utils.GetQueryAndFormString("Enabled", this, 6,1, DataType.Bool);
            normal_channel.IsNav = (bool)Utils.GetQueryAndFormString("IsNav", this, 6,1, DataType.Bool);
            normal_channel.DefaultThumbs = (Int32)Utils.GetQueryAndFormString("DefaultThumbs", this, 10, 1, DataType.Int);
            normal_channel.IsPost = (bool)Utils.GetQueryAndFormString("IsPost", this, 6,1, DataType.Bool);
            normal_channel.IsHtml = (bool)Utils.GetQueryAndFormString("IsHtml", this, 6,1, DataType.Bool);
            normal_channel.ReadGroup = (Int32)Utils.GetQueryAndFormString("ReadGroup", this, 10, 0, DataType.Int);
            normal_channel.IsPart = (Byte)Utils.GetQueryAndFormString("IsPart", this, 3, 0, DataType.Byte);
            normal_channel.HtmlInfo = (String)Utils.GetQueryAndFormString("HtmlInfo", this, 2147483647, 0, DataType.Str);
            normal_channel.SiteSeoBottom = (String)Utils.GetQueryAndFormString("SiteSeoBottom", this, 1000, 0, DataType.Str);
            normal_channel.SiteImg = (String)Utils.GetQueryAndFormString("SiteImg", this, 200, 0, DataType.Str);
           
            QueryParam qp = new QueryParam();
            qp.PageIndex = 1;
            qp.PageSize = 1;
          
            qp.Where = string.Concat("ID=", normal_channel.ReId);
            List<Normal_ChannelEntity> parentChannnelList = Normal_ChannelSv.List(qp, out recordNum);
            Normal_ChannelEntity parentChannel = null;
            if (parentChannnelList.Count > 0)
            {
                parentChannel = parentChannnelList[0];
            }

            qp.Orderfld = " path desc ";
            qp.Where = string.Concat("reid=", normal_channel.ReId);
            
           
            List<Normal_ChannelEntity> channnelList = Normal_ChannelSv.List(qp, out recordNum);
            if (channnelList.Count > 0) //有子栏目
            {
               
                if (parentChannel == null) //是否第一个栏目
                {
                    reid = Utils.StringToInt(channnelList[0].Path, 0);
                    reid = reid + 1;
                    path = Utils.GetFillString(reid.ToString(), "0", 3, true);
                }
                else
                {
                    switch (parentChannel.Path.Length)
                    {
                        case 3:
                            {
                                reid = Utils.StringToInt(Utils.CutString( channnelList[0].Path.ToString(),3,3), 0);
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 3, true);
                                break;
                            }
                        case 6:
                            {
                                reid = Utils.StringToInt(Utils.CutString(channnelList[0].Path.ToString(), 6,2), 0);
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;

                            }
                        case 8:
                            {
                                reid = Utils.StringToInt(Utils.CutString(channnelList[0].Path.ToString(), 8, 2), 0);
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;
                            }
                        case 10:
                            {
                                reid = Utils.StringToInt(Utils.CutString(channnelList[0].Path.ToString(), 10, 2), 0);
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;
                            }
                        case 12:
                            {
                                reid = Utils.StringToInt(Utils.CutString(channnelList[0].Path.ToString(), 12, 2), 0);
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;
                            }
                    }

                    path = string.Concat(parentChannel.Path, path);
                }
            }
            else  //无子栏目
            {
                if (parentChannel == null)  //是否第一个栏目
                {
                    reid = reid + 1;
                    path = Utils.GetFillString(reid.ToString(), "0", 3, true);
                }
                else
                {
                    switch (parentChannel.Path.Length)
                    {
                        case 3:
                            {
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 3, true);
                                break;
                            }
                        case 6:
                            {
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;

                            }
                        case 8:
                            {
                                reid = reid + 1;
                                path = Utils.GetFillString(reid.ToString(), "0", 2, true);
                                break;
                            }
                    }

                    path = string.Concat(parentChannel.Path, path);
                }

            }
            normal_channel.Path = path;

            if (Normal_ChannelSv.Insert(normal_channel) == "")
            {
                returnJson = "{success:'true'}";
                CMN.Framework.MvcWebCacheManager.RemoveNormal_ChannelList();
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 删除频道
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                Normal_ChannelEntity normal_channel = new Normal_ChannelEntity();
                
                normal_channel.Id = intId;
                IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
                string strRetun = Normal_ChannelSv.Delete(normal_channel);
                if (strRetun== "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false',message:'"+strRetun+"'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除频道
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            //Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            //if (regex.IsMatch(actionId))
            //{

            //    IDataService<Normal_ChannelEntity> Normal_ChannelSv = ServiceBuilder.BuildNormal_ChannelService();
            //    if (Normal_ChannelSv.DeleteList(actionId))
            //    {
            //        returnJson = "{success:'true'}";
            //    }
            //    else
            //        returnJson = "{success:'false'}";

            //}
            //else
            //{
            //    returnJson = "{success:'false',message:'参数类型不正确'}";
            //}
            //return returnJson;
            return "";
        }

    }
}
